package com.atguigu.ucenter.controller;


import com.atguigu.base.ExceptionHnadler.CustomException;
import com.atguigu.ucenter.entity.Member;
import com.atguigu.ucenter.service.MemberService;
import com.atguigu.ucenter.vo.LoginVo;
import com.atguigu.ucenter.vo.RegisterVo;
import com.atguigu.utils.JwtUtils;
import com.atguigu.utils.R;
import com.atguigu.utils.vo.UcenterMemberOrder;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author ld
 * @since 2022-08-21
 */
@RestController
@RequestMapping("/ucenter/member")
//@CrossOrigin
public class MemberController {
    @Resource
    private MemberService memberService;
    //登录
    @PostMapping("/login")
    public R login(@RequestBody LoginVo member){
        String token=memberService.login(member);
        if(!StringUtils.isEmpty(token)){
            return R.ok().data("token",token);
        }else {
            return R.error().message("登录失败");
        }

    }
    //注册
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo){
        boolean isRegister = memberService.register(registerVo);
        if(isRegister){
            return R.ok();
        }else{
            return R.error();
        }

    }
    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            Member member = memberService.getById(memberId);
            return R.ok().data("userInfo",member);
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("获取用户信息失败");
        }
    }
    //根据用户id,获取用户信息
    @GetMapping("/getMemberInfo/{memberId}")
    public UcenterMemberOrder getMemberInfo(@PathVariable("memberId")String memberId){
        Member member = memberService.getById(memberId);
        UcenterMemberOrder ucenterMemberOrder=new UcenterMemberOrder();
        BeanUtils.copyProperties(member,ucenterMemberOrder);
        return ucenterMemberOrder;
    }
    //获取每次注册的人数
    @GetMapping("/getCouontRegister/{day}")
    public R getCountRegister(@PathVariable("day")String day){
        Integer countRegister=memberService.getCountRegister(day);
        return R.ok().data("countRegister",countRegister);
    }
}

